<?php
/**
 * bs多规格sku商城系统
 * ============================================================================
 * 版权所有 2024-2099 wltx666.com，并保留所有权利。
 * 网站地址: https://wltx666.com
 * ============================================================================
 * Author: 草上飞
 * Email: wltx@alipay168.cn
 * QQ: 2719875001
 * Date: 2024/12/20
 * 描述:
 */

namespace app\result\goods;

use app\model\goods\GoodsCategory;
use app\result\BaseResult;

class GoodsCategoryResult extends BaseResult
{
    public function __construct()
    {
        parent::__construct();
        $this->model = new GoodsCategory();
    }

    public function list($args = [])
    {
        $keyword = $args['keyword'] ?? '';
        $page = intval($args['page'] ?? 1);
        $pageSize = intval($args['limit'] ?? 10);
        $category_id = intval($args['category_id'] ?? 0);
        $getChild = intval($args['getChild'] ?? 0);
        $where = [];
        if ($keyword) {
            $where['name'] = ['like', '%' . $keyword . '%'];
        }

        if ($category_id) {
            $where['pid'] = $category_id;
        }
        $model = $this->model;
        if ($getChild) {
            $total = $this->model->data_count($where);
            $data = $this->model->data_list($where, '*', 'category_id desc', $page, $pageSize)?->toArray();
            if ($data) {
                foreach ($data as &$value) {
                    $value['is_category'] = false;
                    $value['uniqid'] = get_random(32, true);
                    $value['hasChildren'] = false;
                    $value['children'] = [];
                    //是否启用,1=启用中，0=已下线
                    if ($value['status'] == 1) {
                        $value['status_desc'] = '启用中';
                    } elseif ($value['status'] == -1) {
                        $value['status_desc'] = '已禁用';
                    }
                }
                unset($value);
            }
            return $this->success_return('success', [
                'total' => $total,
                'list' => $data
            ]);
        }


        $whereAll = [['pid', '=', 0]];
        $data = $model->data_list_nopage($whereAll);

        foreach ($data as &$value) {
            $value['is_category'] = true;
            $value['uniqid'] = get_random(32, true);
            $value['hasChildren'] = $model->data_count(['category_id' => $value['category_id']]) > 0;
            if ($value['status'] == 1) {
                $value['status_desc'] = '启用中';
            } elseif ($value['status'] == -1) {
                $value['status_desc'] = '已禁用';
            }
        }
        unset($value);


        return $this->success_return('success', [
            'data' => $data,
            'total' => count($data)
        ]);
    }

    public function get($args)
    {
        $category_id = $args['id'] ?? 0;
        $data = $this->model->data_get(['category_id' => $category_id]);
        if (!$data) {
            return self::error_return('数据不存在');
        }
        if ($data['pid'] > 0) {
            $data['parent_name'] = $this->model->get_value(['category_id' => $data['pid']], 'name');
        }
        return self::success_return('success', [
            'info' => $data
        ]);
    }


    public function save_data($args)
    {
        $baseData = [
            'category_id' => $args['category_id'] ?? 0,
            'name' => $args['name'] ?? '',
            'pid' => $args['pid'] ?? 0,
            'sort' => $args['sort'] ?? 0,
            'image' => $args['image'] ?? '',
            'status' => $args['status'] ?? 1,
            'del_time' => $args['del_time'] ?? 0,
        ];
        if ($baseData['category_id']) {

            if (!empty($baseData['pid']) && $baseData['pid'] == $baseData['category_id']) {
                return self::error_return('上级分类不能为当前分类');
            }

            (new GoodsCategory())->data_update(['category_id' => $baseData['category_id']], $baseData);
            $category_id = $baseData['category_id'];
        } else {
            unset($baseData['category_id']);
            $category_id = (new GoodsCategory())->data_add($baseData);
            if (!$category_id) {
                return self::error_return('保存失败');
            }
        }
        return self::success_return('保存成功');
    }

    public function del_data($args)
    {
        $category_id = $args['id'] ?? 0;
        if (!$category_id) {
            return self::error_return('参数错误');
        }
        $data = (new GoodsCategory())->data_get(['category_id' => $category_id]);
        if (!$data) {
            return self::error_return('数据不存在');
        }
        $child = (new GoodsCategory())->data_count(['pid' => $category_id]);
        if ($child) {
            return self::error_return('请先删除子分类');
        }
        $res = $data->delete();
        if (!$res) {
            return self::error_return('删除失败');
        }
        return self::success_return('删除成功');
    }

    public function set_status($args): array
    {
        $category_id = $args['id'] ?? 0;
        if (!$category_id) {
            return self::error_return('参数错误');
        }
        $data = (new GoodsCategory())->data_get(['category_id' => $category_id]);
        if (!$data) {
            return self::error_return('数据不存在');
        }
        $res = (new GoodsCategory())->data_update(['category_id' => $category_id], ['status' => $data['status'] == 1 ? -1 : 1]);
        if (!$res) {
            return self::error_return('操作失败');
        }
        return self::success_return('操作成功');
    }

    public function copy($args): array
    {
        $category_id = $args['id'] ?? 0;
        if (!$category_id) {
            return self::error_return('参数错误');
        }
        $data = (new GoodsCategory())->data_get(['category_id' => $category_id]);
        if (!$data) {
            return self::error_return('数据不存在');
        }
        unset($data['category_id']);
        $data['name'] = $data['name'] . '(复制)';
        $data['del_time'] = 0;
        $data['status'] = -1;//禁用
        $res = (new GoodsCategory())->data_add($data);
        if (!$res) {
            return self::error_return('复制失败');
        }
        return self::success_return('复制成功');
    }

    public function list_options($args = [])
    {
        $all = (new GoodsCategory())->data_list_nopage([
            'del_time' => 0,
            'status' => 1
        ], 'category_id as id,name as label,category_id as value,pid');
        if ($all) {
            $all = getTree($all, 'id', 'pid');
        }
        return self::success_return('success', [
            'list' => $all,
        ]);
    }

    public function api_list($args = [])
    {
        $model = new GoodsCategory();
        $where = [
            'del_time' => 0,
            'status' => 1
        ];
        $field = 'category_id as id,name,pid,sort,image,status';
        $category = $model->data_list_nopage($where, $field, 'pid asc,sort desc');

        $config = [
            'category_style' => 20,//20=二级分类/10=一级分类（大图）/11=一级分类铺开（小图）/30=三级分类(必须有三级)
            'share_title' => '分类页面',
            'color2' => '#fad400',
            'color1' => '#E85A71',
            'file_path' => null,
            'file_name' => null,
            'file_url' => null
        ];
        return self::success_return('success', [
            'category' => $category,
            'config' => $config
        ]);
    }
}
